const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');
class UserController extends Controller {
         //注册 
   async registry() {
        const { ctx } = this;
        //获取参数
        let { name, pwd } = ctx.request.body;
        if (!name || !pwd) {
            ctx.body = {
                code: 2,
                mes: '缺少参数'
            }
            return;
        }
        let user = await ctx.service.user.getuser(name);
        if (user.length > 0) {
            ctx.body = {
                code: 3,
                mes: '用户已经注册'
            }
            return;
        }
        let res = await ctx.service.user.registry(name, ctx.helper.help(pwd));
        if (res.affectedRows == 1) {
            ctx.body = {
                code: 0,
                mes: '注册成功'
            }
        } else {
            ctx.body = {
                code: 1,
                mes: '注册失败'
            }
        }
    }
    async login() { //登录
        const { ctx } = this;
        let { name, pwd } = ctx.request.body;
        if (!name || !pwd) {
            ctx.body = {
                code: 2,
                mes: '缺少参数'
            }
            return;
        }
        let user = await ctx.service.user.getuser(name);
        if (user.length == 0) {
            ctx.body = {
                code: 3,
                mes: '请先注册'
            }
            return;
        }
        let res = await ctx.service.user.login(name,  ctx.helper.help(pwd));
        const token = jwt.sign({...res[0]},ctx.app.config.keys,{expiresIn:'10h'}); //生成token
        if (res.length > 0) {
            ctx.body = {
                code: 0,
                token,
                mes: '登陆成功'
            }
        } else {
            ctx.body = {
                code: 1,
                mes: '登陆失败'
            }
        }
    }
}
module.exports = UserController;